using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace OA.Mvc3
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801
    
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
                , new string[] { "OA.Mvc3.Controllers" }
            );
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }


        protected void Application_End(object sender, EventArgs e)
        {
            BLL.DB_help.NHibernateHelper.CloseAllSessionFactory();
        }

        protected void Session_Start(object sender, EventArgs e)
        {
                
        }

        protected void Session_End(object sender, EventArgs e)
        {
            //清除离线用户session
            var index=BLL.LoginUser.OnLineManagers.FindIndex(r => r.SessionID == Session.SessionID);
            if (index >= 0)
            {
                lock (BLL.LoginUser.OnLineManagers)
                {
                    BLL.LoginUser.OnLineManagers.RemoveAt(index);
                }
            }
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //Response.Filter = new UI.HtmlFilter(Response.Filter);  //内容过虑器
            #region 防止swfupload创建新的session被登陆验证拦截
            try
            {
                string value = Common.DTRequest.GetString(Common.Keys.session_param_name);
                if (!string.IsNullOrEmpty(value))
                {
                    Common.Utils.WriteCookie(Common.Keys.session_cookie_name, value);
                }
            }
            catch (Exception)
            {
                Response.StatusCode = 500;
                Response.Write("Error Initializing Session");
            }
            #endregion
        }

        protected void Application_EndRequest(Object sender, EventArgs e)
        {
            BLL.DB_help.NHibernateHelper.CloseAllSession();
            #region 记录hql
            if (BLL.SystemConfig.LoadConfig().Feature.IsLogHQL && Context.Items[Common.Keys.LogHqlKey] != null)
            {
                string log = Request.Url.PathAndQuery + "\r\n";
                log += Context.Items[Common.Keys.LogHqlKey].ToString();
                Common.Log.WriteLog(Common.LogFile.SQL, log);
            }
            #endregion
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            BLL.DB_help.NHibernateHelper.ClearAllState(); //清除hql信息
            Exception LastError = Server.GetLastError();

            #region 系统错误日志

            string msg = string.Format("错误类型：{0}\r\n错误描述：{1}\r\n访问地址：{2}\r\n客户IP:{3}\r\n调用堆栈：\r\n{4}"
                , LastError.GetType().FullName, LastError.Message, Request.Url.PathAndQuery, Request.UserHostAddress, LastError.StackTrace);
            Common.Log.WriteLogAsyn(Common.LogFile.Error, msg);

            #endregion

            #region 发送错误邮件

            if (BLL.SystemConfig.LoadConfig().Feature.IsErrorAutoSendMail)
            {
                var logModel = new
                {
                    ErrorType = LastError.GetType().FullName,
                    ErrorMessage = LastError.Message,
                    PathAndQuery = Request.Url.PathAndQuery,
                    ClientIP = Request.UserHostAddress,
                    ErrorTime = DateTime.Now,
                    StackTrace = LastError.StackTrace
                };
                BLL.Mail.MailNotifyByEvent("SystemError", "SystemError", "Error", logModel);
            }
            #endregion
        }
    }
}